<?php

namespace App\Http\Controllers\Admin;

use App\Category as CategoryModel;
use \Request;

class Category extends Base
{
    public function index()
    {
        $map          = Request::all();
        $categoryList = CategoryModel::orderBy('id', 'desc')
            ->where(function ($query) use ($map) {
                if (isset($map['title']) && $map['title'] !== '') {
                    $query->where('title', 'like', '%' . $map['title'] . '%');
                }
            })
            ->paginate(15);
        //分页搜索条件
        $categoryList->appends([
            'title' => Request::get('title', ''),
        ]);
        $count = CategoryModel::count();
        return view('admin.category.index', [
            'count'        => $count,
            'get'          => $map,
            'categoryList' => $categoryList,
        ]);
    }

    public function create()
    {
        return view('admin.category.create');
    }

    public function store(Request $request)
    {
        $result = CategoryModel::create([
            'title'   => Request::input('title', ''),
            'sort'    => Request::input('sort', '0'),
            'is_show' => Request::input('is_show', '0'),
        ]);
        return $result ? showSuccess('添加分类成功！') : showError('添加分类失败！');
    }

    public function edit($id = '')
    {
        $categoryInfo = CategoryModel::find($id);
        return view('admin.category.edit', ['info' => $categoryInfo]);
    }

    public function update($id = '')
    {
        $result = CategoryModel::where('id', '=', $id)->update([
            'title'   => Request::input('title', ''),
            'sort'    => Request::input('sort', '0'),
            'is_show' => Request::input('is_show', '0'),
        ]);
        return $result ? showSuccess('修改分类成功！') : showError('修改分类失败！');
    }

    public function destroy($id = '')
    {
        $result = CategoryModel::where('id', '=', $id)->delete();
        return $result ? showSuccess('删除分类成功！') : showError('删除分类失败！');

    }
}
